//
//  ContactsTableViewController.swift
//  WeiXin1.0
//
//  Created by xyy on 2017/11/6.
//  Copyright © 2017年 xyy. All rights reserved.
//

import UIKit

class ContactsTableViewController: UITableViewController {

    var contactArr: NSMutableArray!
    var sectionsArray: NSMutableArray!
    var collation: UILocalizedIndexedCollation!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "通信录"
        configureSections()
    }

    func configureSections() {
        self.tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "cell")
        self.sectionsArray = NSMutableArray()
        
        //先加入头部信息
        let newFriend: ContactModel = ContactModel.initWithAvatar("new_friend", name: "新的朋友")
        let contactOffical: ContactModel = ContactModel.initWithAvatar("new_friend", name: "公众号")
        let contactTag: ContactModel = ContactModel.initWithAvatar("new_friend", name: "标签")
        let groupChat: ContactModel = ContactModel.initWithAvatar("new_friend", name: "群聊")
        
        let headArr: NSArray = [newFriend,contactOffical,contactTag,groupChat]
        self.sectionsArray.add(headArr)
        
        //初始化测试数据
        self.contactArr = NSMutableArray()
        
        let strPath = Bundle.main.path(forResource: "Contact", ofType: "plist")
        
        let array: NSArray = NSArray(contentsOfFile: strPath!)!
        
        
        for dict in array {
            let model = ContactModel(dic: dict as!
                [String : AnyObject])
            self.contactArr.add(model)
        }
        
        //获取当前uilocalizedindexedcollation对象并且引用赋给collation，a-z数据
        self.collation = UILocalizedIndexedCollation.current()
        
        //获取索引值和section标题数
        let sectionTitlesCount: NSInteger = self.collation.sectionTitles.count
        
        var newSectionsArray = [Any]()
        
        //设置sections数组初始化： 元素包含userobjs数据的空数据
        for _ in 0..<sectionTitlesCount{
            let array: NSMutableArray = NSMutableArray()
            newSectionsArray.append(array)
        }
        
        //将用户数据进行分类，存贮到对应sesion数组
        for contact in self.contactArr {
            let sectionNumber: NSInteger = self.collation.section(for: contact, collationStringSelector:#selector(getter: (contact as! ContactModel).name))
            
            //获取section的数组
            let sectionUserObjs: NSMutableArray = newSectionsArray[sectionNumber] as! NSMutableArray
            sectionUserObjs.add(contact)
        }
        
        
        self.sectionsArray.addObjects(from: newSectionsArray)
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return self.collation.sectionTitles.count+1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        let UserObjsSection: NSArray = self.sectionsArray.object(at: section) as! NSArray
        return UserObjsSection.count
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for:indexPath)
        
        let userNameInsection: NSArray = self.sectionsArray.object(at: indexPath.section) as! NSArray
        
        let contact: ContactModel = userNameInsection.object(at: indexPath.row) as! ContactModel
        cell.textLabel?.text = contact.name;
        cell.imageView?.image = UIImage(named:contact.avatar)
        
        return cell
    }
    
    
    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if section != 0{
            let UserObjsInSection: NSArray = self.sectionsArray.object(at: section) as! NSArray
            if UserObjsInSection.count<=0 {
                return nil
            }
            return self.collation.sectionTitles[section - 1]
        }
        return nil
    }
    
    //设置索引标题
    override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return self.collation.sectionTitles
    }
    
    //关联搜索
    override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        return self.collation.section(forSectionIndexTitle: index)
    }

    
    
}
